import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Input, Popconfirm, Table, Tag } from 'antd';
import dayjs from 'dayjs';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  proInspectionRecordDelete,
  proInspectionRecordPage
} from '@/services/bizApi/shengchanxunjianjilujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Detail, { DetailRef } from './detail';
import Edit, { EditRef } from './edit';

/** 详情 */

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProInspectionRecordQuery;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const detail = useRef<DetailRef>(null);

  const [filter] = Filter.useForm();

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await proInspectionRecordPage({
        ...formData,
        ...id,
        inspectionStartTime: formData.inspectionDate
          ? dayjs(formData.inspectionDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        inspectionEndTime: formData.inspectionDate
          ? dayjs(formData.inspectionDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        taskStartTimeStart: formData.taskDate
          ? dayjs(formData.taskDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        taskStartTimeEnd: formData.taskDate
          ? dayjs(formData.taskDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });
      // [
      //     {
      //       beginTime: '',
      //       endTime: '',
      //       recordId: 5123123,
      //       taskId: 4123123,
      //       taskName: '',
      //       taskStartTimeStart: '',
      //       taskStartTimeEnd: '',
      //       inspectionUserId: 12312,
      //       inspectionUserName: '',
      //       inspectionStartTime: '',
      //       inspectionEndTime: '',
      //       status: 1
      //     }
      //   ]
      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter} extra={<></>}>
        <Filter.Item name="taskName">
          <Input
            style={{
              width: 180
            }}
            placeholder="任务名称"
          />
        </Filter.Item>
        <Filter.Item name="taskDate">
          <DatePicker.RangePicker placeholder={['计划开始时间', '计划结束时间']} />
        </Filter.Item>
        <Filter.Item name="inspectionDate">
          <DatePicker.RangePicker placeholder={['巡检开始时间', '巡检结束时间']} />
        </Filter.Item>

        <ProFormSelect
          name="inspectionUserId"
          style={{ width: 180 }}
          label=""
          placeholder="请选择巡检人员"
          showSearch={true}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });

            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '任务名称',
            dataIndex: 'taskName'
          },
          {
            title: '计划开始时间',
            dataIndex: 'taskStartTime',
            render: (text, row) => <div>{text ? dayjs(text).format('YYYY-MM-DD') : ''}</div>
          },
          // {
          //   title: '巡检人员',
          //   dataIndex: 'inspectionUserName'
          // },
          // {
          //   title: '巡检开始时间',
          //   dataIndex: 'inspectionStartTime',
          //   render: (text, row) => (
          //     <div>{text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''}</div>
          //   )
          // },
          // {
          //   title: '巡检结束时间',
          //   dataIndex: 'inspectionEndTime',
          //   render: (text, row) => (
          //     <div>{text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''}</div>
          //   )
          // },
          {
            title: '巡检状态',
            dataIndex: 'status',
            render: (status, row) => {
              return status == 1 ? (
                <Tag color="warning">待巡检</Tag>
              ) : status == 2 ? (
                <Tag color="processing">巡检中</Tag>
              ) : status == 3 ? (
                <Tag color="success">已巡检</Tag>
              ) : (
                ''
              );
            }
          },
          {
            title: '是否异常',
            dataIndex: 'normal',
            render: (val, row) => {
              return (
                <Text.Space>
                  {val == null ? (
                    <Tag color="success">正常</Tag>
                  ) : !val ? (
                    <Tag color="red">异常</Tag>
                  ) : (
                    <Tag color="success">正常</Tag>
                  )}
                </Text.Space>
              );
            }
          },
          {
            title: '巡检进度',
            dataIndex: '',
            render: (_, row) => (
              <Text
                type="primary"
                onClick={() => {
                  detail.current?.open({
                    id: row.recordId as unknown as string,
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
              >
                查看详情
              </Text>
            )
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该条巡检记录吗？`}
                      onConfirm={async () => {
                        const res = await proInspectionRecordDelete({
                          id: row.recordId as unknown as string
                        });
                        store.app?.message.success('删除成功');
                        table.refresh();
                      }}
                    >
                      <Text>删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="recordId"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />

      <Detail ref={detail} />
    </>
  );
};

export default Page;
